package net.zio.kamenriderzioaddon.network;

import net.minecraft.Util;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.saveddata.SavedData;
import net.minecraftforge.network.PacketDistributor;

import net.zio.kamenriderzioaddon.KamenRiderZioAddonMod;
import net.zio.kamenriderzioaddon.network.NetworkHandler;
import net.zio.kamenriderzioaddon.network.message.SyncPlayerDataPacket;


/**
 * 保存世界数据
 *
 * @author QianYunYi
 */
public class AddonWorldData extends SavedData {
    private static final String DATA_NAME = "kamen_rider_zio_addon_world";
    public static AddonWorldData clientSide = new AddonWorldData();

    @Override
    public CompoundTag save(CompoundTag nbt) {
        // 保存数据
        return nbt;
    }

    public static AddonWorldData load(CompoundTag tag) {
        AddonWorldData data = new AddonWorldData();
        // 读取数据
        return data;
    }

    public static AddonWorldData get(LevelAccessor world) {
        if (world instanceof ServerLevel level) {
            return level.getDataStorage()
                    .computeIfAbsent(AddonWorldData::load, AddonWorldData::new, DATA_NAME);
        } else {
            return clientSide;
        }
    }

    public CompoundTag serializeNBT() {
        return save(new CompoundTag());
    }

    // 同步数据到客户端
    public void sync(LevelAccessor world) {
        setDirty();
        if (!world.isClientSide()) {
            NetworkHandler.CHANNEL.send(
                    PacketDistributor.DIMENSION.with(() -> ((Level) world).dimension()),
                    new SyncPlayerDataPacket(this.save(new CompoundTag()), Util.NIL_UUID)
            );
        }
    }
}